package com.h5;

import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyz.service.CouponService;
import com.cyz.service.UserCouponService;
import com.demo.annotation.LoginFilter;
import com.demo.util.DateUtil;
import com.demo.util.JSONUtils;
import com.demo.util.ProperityUtil;
import com.shopcart.domain.Order;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreComment;
import com.shopcart.domain.StoreGoods;
import com.shopcart.domain.StoreGoodsCategory;
import com.shopcart.domain.StorePhoto;
import com.shopcart.service.OrderService;
import com.shopcart.service.StoreCommentService;
import com.shopcart.service.StoreGoodsCategoryService;
import com.vsd.domain.Coupon;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StorePhotoService;
import com.vsd.service.StoreService;
import com.vsd.service.UserCollectService;
import com.zy.store.proto.MOAppStore.MFoodDetail;
import com.zy.store.proto.MOAppStore.MStore;

@RequestMapping("/m/store")
@Controller
public class H5StoreController extends H5BaseController{

	@Autowired
	CouponService couponService;
	@Autowired
	UserCouponService userCouponService;
	@Autowired
	StoreService storeService;
	@Autowired
	StoreGoodsService storeGoodsService;
	@Autowired
	StoreGoodsCategoryService storeGoodsCategoryService;
	@Autowired
	StoreCommentService storeCommentService;
	@Autowired
	UserCollectService userCollectService;
	@Autowired
	OrderService orderService;
	@Autowired
	StorePhotoService storePhoneService;
	@Autowired
	ProperityUtil properityUtil;
	
	@RequestMapping("/coupon")
	@ResponseBody
	public String couponList(String id,Integer page,Integer limit){
		Page<Coupon> list = couponService.findByStoreIdAndSource(id, 2, new PageRequest(page, limit,new Sort(Direction.DESC, "createTime")));
		return JSONUtils.serialize(list);
	}
	
	@RequestMapping("/diancan/{id}")
	public String diancai(@PathVariable("id")String id,ModelMap map){
		map.put("id", id);
		return BASE_PATH+"/diancan";
	}
	
	@RequestMapping("/addDiacan/{id}")
	public String addDiancan(@PathVariable("id")String id,ModelMap map){
		map.put("id", id);
		return BASE_PATH+"/addDiancan";
	}
	@RequestMapping("/photos/{id}")
	public String photos(@PathVariable("id")String id,ModelMap map){
		map.put("id", id);
		return BASE_PATH+"/photos";
	}
	
	@RequestMapping("/map/{id}")
	public String map(@PathVariable("id")String id,ModelMap map){
		map.put("id", id);
		return BASE_PATH+"/storeMap";
	}
	
	@RequestMapping("/getCoupon")
	@ResponseBody
	@LoginFilter(outpage="/m/login")
	public String getCoupon(String id,HttpSession session){
		Ret ret = userCouponService.getCoupon(id, getSessionParameter(session, "id"));
		return JSONUtils.serialize(ret);
	}
	
	//商家店内团购商品 
	@RequestMapping("/storeTg")
	@ResponseBody
	public String storeTgList(String id){
		Store store = storeService.findById(id);
		if(store==null) return JSONUtils.serialize(new Ret(-1, "商家不存在"));
		Collection<StoreGoods> list  = storeGoodsService.findByStoreIdAndType(id, 2);
		return JSONUtils.serialize(new Ret(0, list));
	}
	
	//商家店内分类商品
	@RequestMapping("/goodsList")
	@ResponseBody
	public String storeGoodsList(String id){
		Store store = storeService.findById(id);
		if(store==null) return JSONUtils.serialize(new Ret(-1, "商家不存在"));
		JSONObject ret = new JSONObject();
		ret.put("store", store);
		//查找分类
		Collection<StoreGoodsCategory> list = storeGoodsCategoryService.findByStoreId(id, new Sort(Direction.DESC, "sort"));
		JSONArray array = new JSONArray();
		for (StoreGoodsCategory category : list){
			JSONObject data = new JSONObject();
			data.put("cate", category);
			data.put("goods", storeGoodsService.findList(id, category.getId(), category.getName()));
			array.add(data);
		}
		ret.put("data", array);
		return JSONUtils.serialize(new Ret(0, ret));
	}
	
	@RequestMapping("/detail")
	@ResponseBody
	public String detail(String id,HttpSession session){
		return storeService.findStore(id, getSessionParameter(session, "id"));
	}
	
	@RequestMapping(value="/commentList",method=RequestMethod.POST)
	@ResponseBody
	public String commentList(String id,Integer page,Integer limit){
		return storeCommentService.findByStore(id, page, limit);
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public String list(String areaCode,String catecode,Integer sort,String lat,String lng,Integer page,Integer limit){
		if(sort==null) sort = 1;
		return storeService.selectList(catecode, areaCode, lat, lng, page, limit);
	}
	
	@RequestMapping("/tgDetail")
	@ResponseBody
	public String tgList(String id,HttpSession session){
		StoreGoods goods = storeGoodsService.findById(id);
		if (goods == null) return JSONUtils.serialize(new Ret(-1,"商品不存在"));
		String userId = getSessionParameter(session, "id");
		MStore.Builder store = storeService.findStoreDetail(id, userId);
		
		JSONObject ret = new JSONObject();
		ret.put("beforeBuy", properityUtil.getSelf_url()+"/detail?id="+id+"&type=2");
		ret.put("name", goods.getName());
		ret.put("imgs", goods.getImgs());
		ret.put("oldPrice", goods.getOldPrice().toString());
		ret.put("nowPrice", goods.getNowPrice().toString());
		ret.put("remark", properityUtil.getSelf_url()+"/detail?id="+id+"&type=1");
		ret.put("storeId", goods.getStoreId());
		ret.put("isCollect", 0);
		ret.put("goodsContent", goods.getGoodsContent());
		if (StringUtils.isNoneBlank(userId)){
			int c = userCollectService.isCollect(userId, 1, id);
			if(c>0) ret.put("isCollect",1);
		}
		ret.put("storeName", store.getName());
		ret.put("star", store.getStar());
		ret.put("commentCnt", store.getCommentCnt());
		ret.put("address", store.getAddress());
		ret.put("img", store.getLogo());
		
		return JSONUtils.serialize(new Ret(0,ret));
	}
	
	@RequestMapping("/foodDetail")
	@ResponseBody
	public String foodDetail(String id){
		MFoodDetail.Builder ret = MFoodDetail.newBuilder();
		StoreGoods goods = storeGoodsService.findById(id);
		if(goods==null) return JSONUtils.serialize(new Ret(-1,"商品不存在"));
		
		ret.setImgs(goods.getImgs());
		ret.setName(goods.getName());
		ret.setNowPrice(goods.getNowPrice().toString());
		ret.setRemark(properityUtil.getSelf_url()+"/detail?id="+id+"&type=1");
		//月销量
		int sell = orderService.selectGoodsSellCnt(id, DateUtil.getFirstOfMonth()+" 00:00:00", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
		ret.setOldPrice((goods.getSellBase()+sell)+"");
		return JSONUtils.serialize(new Ret(0,ret));
	}
	
	/**
	@api mPhotoList mPhotoList	//商家相册
	@param optional string id  //商家id
	@return MPhotoList
	*/
	@RequestMapping("/photoList")
	@ResponseBody
	public String mPhotoList(HttpSession session,String id) throws Exception {
		Collection<StorePhoto> list = storePhoneService.findByStoreId(id);
		return JSONUtils.serialize(list);
	}
	
	@RequestMapping("/comment")
	@ResponseBody
	@LoginFilter(outpage="/m/login")
	public String comment(HttpSession session, String orderId, Integer score,
			String content, String imgs) {
		// 找到该订单
		Order order = orderService.findById(orderId);
		// 订单是否已评价
		if (order == null || order.getHasComment() == 1
				|| order.getState() != 4) {
			return JSONUtils.serialize(new Ret(-1, "订单无法评价"));
		}
		// 新增商家评价
		StoreComment comment = new StoreComment();
		comment.setContent(content);
		comment.setCreateTime(new Date());
		comment.setImgs(imgs);
		comment.setOrderId(orderId);
		comment.setScore(score);
		comment.setStoreId(order.getStoreId());
		comment.setUserId(getSessionParameter(session, "id"));
		comment.setShowName(1);
		storeCommentService.save(comment);
		return JSONUtils.serialize(new Ret(0));
	}
}
